<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage, ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getDepartmentTableApi,
  saveDepartmentApi,
  deleteDepartmentApi
} from '@/api/department/index'
import type { DepartmentItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getDepartmentTableApi()
    return {
      list: res.data,
      total: res.data.length
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDepartmentApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const searchParams = ref({})

pageSize.value = 20
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'userName',
    label: t('userDemo.departmentName'),
    form: {
      component: 'Input',
      componentProps: {
        clearable: false
      }
    }
  },
  {
    field: 'enabled',
    label: t('userDemo.status'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const status = data.row.enabled
          return (
            <>
              <ElTag type={status ? 'success' : 'danger'}>
                {status ? t('userDemo.enable') : t('userDemo.disable')}
              </ElTag>
            </>
          )
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        clearable: false,
        options: [
          {
            value: false,
            label: t('userDemo.disable')
          },
          {
            value: true,
            label: t('userDemo.enable')
          }
        ]
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          const status = data.enabled
          return (
            <>
              <ElTag type={status ? 'success' : 'danger'}>
                {status ? t('userDemo.enable') : t('userDemo.disable')}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: () => {
          return <>{new Date('2024-06-24').toLocaleDateString()}</>
        }
      }
    },
    detail: {
      slots: {
        default: () => {
          return <>{new Date('2024-06-24').toLocaleDateString()}</>
        }
      }
    },
  },
  {
    field: 'role',
    label: '角色',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        clearable: false,
        props: {
          label: 'label'
        },
        options: [{
          label: '管理员',
          value: 'admin'
        }, {
          label: '委办局',
          value: 'department'
        }]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const role = data.row.role == 'admin' ? '管理员' : '委办局'
          return <>{role}</>
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          const role = data.role == 'admin' ? '管理员' : '委办局'
          return <>{role}</>
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentItem | null>(null)
const actionType = ref('')

const AddAction = () => {
  // dialogTitle.value = t('exampleDemo.add')
  // currentRow.value = null
  // dialogVisible.value = true
  // actionType.value = ''
  ElMessage.warning('该功能暂未开放')
}

const delLoading = ref(false)

const delData = async (_row: DepartmentItem | null) => {
  // const elTableExpose = await getElTableExpose()
  // ids.value = row
  //   ? [row.id]
  //   : elTableExpose?.getSelectionRows().map((v: DepartmentItem) => v.id) || []
  // delLoading.value = true
  // await delList(unref(ids).length).finally(() => {
  //   delLoading.value = false
  // })
  ElMessage.warning('该功能暂未开放')
}

const action = (row: DepartmentItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveDepartmentApi(formData)

    if (res.data === 'success') {
      if (userStore.getUserInfo?.username === formData.name) {
          ElMessage.success('当前用户信息更新成功，即将重新登录以更新权限')
          setTimeout(() => {
            userStore.logout()
          }, 1000);
        } else {
          ElMessage.success('部门信息更新成功')
        }
    } else {
      ElMessage.error('部门信息更新失败，请重试')
    }
    saveLoading.value = false
    dialogVisible.value = false
    currentPage.value = 1
    getList()
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>

    <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
      :data="dataList" :loading="loading" :pagination="{
      total: total
    }" @register="tableRegister" />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :form-schema="allSchemas.formSchema"
      :current-row="currentRow" />

    <Detail v-if="actionType === 'detail'" :detail-schema="allSchemas.detailSchema" :current-row="currentRow" />

    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
